# coding: UTF-8
# @Date    ：2024/10/14 18:23
# @File    : __init__.py
# @Author  : fum


from fastapi import FastAPI, APIRouter
import pkgutil
import importlib
import logging

logger = logging.getLogger(__name__)

api = APIRouter(prefix="/app")


def init_controller(app: FastAPI):
    package = __import__(__package__, fromlist=[''])
    submodules = [name for _, name, _ in pkgutil.iter_modules(package.__path__)]
    for submodule_name in submodules:
        try:
            # 动态导入子模块
            submodule = importlib.import_module(f"{__package__}.{submodule_name}")
            # 尝试从子模块中获取 'api' 变量
            if hasattr(submodule, 'api'):
                api_variable = getattr(submodule, 'api')
                app.include_router(api_variable)
            else:
                print(f"在子模块 {submodule_name} 中未找到 'api' 变量")
        except ImportError as e:
            print(f"无法导入子模块: {submodule_name} ↘ \n【error】:{e}")
